#!/usr/bin/env.python
# _*_ coding:utf-8 _*_
# # # # # # # # # # # # # # # # # # # #
#  题目:      异常处理 Exceptions      #
#  姓名:         李吉辉                #
#  时间:    2018年12月18日16:17:03     #
# # # # # # # # # # # # # # # # # # # #
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
from django.db import DatabaseError

def exception_handler(exc, context):
    # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    response = drf_exception_handler(exc, context)

    # 在此处补充自定义的异常处理
    if response is None:
        view = context['view']
        # 判断异常是否是数据库的异常
        if isinstance(exc, DatabaseError):
            print('[%s]: %s' % (view, exc))
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response